
#include <BFont>
#include <BScrollArea>

#include "member_BListWidget.h"
#include "member_BListItem.h"

using namespace BWE;

member_BListWidget::member_BListWidget(BListWidget* listWidget)
{
	boss = listWidget;
	space = 3;
	multiChoose = false;
	continuChoose = false;
	showItemBegin = 0;
	showItemCount = 0;
	pressedItem = 0;
	hoveredItem = 0;
	dirtyArea = false;
}
member_BListWidget::~member_BListWidget()
{

}

void member_BListWidget::freshArea()
{
	const BFont* font = boss->font();
	if (!font)
		return;

	BRect crect = boss->clientRect();
	int cx = crect.x();
	int cy = crect.y();
	int width = 0;
	int posY = cy;
	for (int i = 0; i < items.size(); i++)
	{
		BListItem* item = items[i].ptr();
		BSize& hintSize = item_member(item)->hintSize;
		if (item_member(item)->dirty)
		{
			item_member(item)->textSize = font->textSize(item->text());
			hintSize = item_member(item)->textSize;
			hintSize.width() += hintSize.height();
			item_member(item)->rect.top() = posY;
			item_member(item)->rect.bottom() = posY + hintSize.height();
			item_member(item)->dirty = false;
		}
		width = bMax(hintSize.width(), width);
		posY += space + hintSize.height();
	}
	minAreaSize.set(width, posY);
	BRect area = boss->area();
	area.setSize(bMax(width, crect.width()), posY);
	boss->setArea(area);
}
void member_BListWidget::freshItemRects()
{
	BRect area = boss->area();
	BRect crect = boss->clientRect();
	int top = crect.top();
	int bottom = crect.bottom();
	int width = crect.width();

	showItemBegin = -1;
	showItemCount = 0;

	int x = area.x();
	int y = area.y();
	for (int i = 0; i < items.size(); i++)
	{
		BListItem* item = items[i].ptr();
		item_member(item)->rect.setPos(x, y);
		y += space + item_member(item)->rect.height();
		if (y >= top)
		{
			showItemBegin = i;
			showItemCount++;
			item_member(item)->rect.setWidth(width);
			item_member(item)->adjust();
			for (i++; i < items.size(); i++)
			{
				BListItem* item = items[i];
				item_member(item)->rect.setPos(x, y);
				item_member(item)->rect.setWidth(width);
				item_member(item)->adjust();
				showItemCount++;
				y += space + item_member(item)->rect.height();
				if (y > bottom)
					break;
			}
			break;
		}
	}
}

void member_BListWidget::select(BListItem* item)
{
	if (continuChoose)
	{
		if (selectedItems.empty())
		{
			boss->setSelected(item, true);
		}
		else
		{
			BList<BListItem*> itemlst;
			BListItem* begin = selectedItems.first();
			items.select(begin, item, itemlst);
			for (auto item : selectedItems)
			{
				if (!itemlst.contain(item))
					boss->setSelected(item, false);
			}
			for (auto item : itemlst)
			{
				if (!selectedItems.contain(item))
					boss->setSelected(item, true);
			}
		}
		return;
	}
	if (multiChoose)
	{
		if (selectedItems.contain(item))
			boss->setSelected(item, false);
		else
			boss->setSelected(item, true);
		return;
	}
	boss->clearSelected();
	boss->setSelected(item, false);		
}
